//
//  UploadVideoController.m
//  CloudTest
//
//  Created by 张帅 on 2020/7/30.
//  Copyright © 2020 张帅. All rights reserved.
//

#import "UploadVideoController.h"
#import "SubmitBtnView.h"
#import "AliOSSObjctManage.h"
#import "UploadVideoCell.h"
#import "UploadSuccessController.h"
@interface UploadVideoController ()
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,strong)SubmitBtnView * bottom_btn;
@property(nonatomic,strong)NSString * orderId;
@property(nonatomic,assign)BOOL cancel_upload;//取消上传 默认 NO
@end

@implementation UploadVideoController
- (instancetype)init
{
    self = [super init];
    if (self) {
        _cancel_upload = NO;
    }
    return self;
}


- (void)setupNavigationItems {
    [super setupNavigationItems];
     self.title = @"视频上传";
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.enabled=NO;//关闭右滑返回
    self.orderId = [TestManageTool sharedInstance].orderModel.orderId;
    self.dataArray = [TestManageTool sharedInstance].dataArray;
    [self.tableView reloadData];
    [self isShowNavBack_pop];
    [self add_bottom_view];
    [self start_upload];//开始上传

}
- (void)initTableView {
    [super initTableView];
    self.tableView.backgroundColor= color(@"#F5F5F5");
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = [self add_header_view];
}
- (UIView *)add_header_view {
    UIView * header_view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44+14)];
    header_view.backgroundColor =  color(@"#F5F5F5");
    UIView * contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    contentView.backgroundColor = color(@"#FF9266");
    [header_view addSubview:contentView];
    UILabel * label = [UIFactory create_LabelContent:@"每首曲目只有三次机会，请尽可能保持录制完成再结束，如果重新录制则之前的记录将会自动删除，请慎重考虑。" textColor:[UIColor whiteColor] fontSize:12];
    label.numberOfLines = 0;
    label.frame = CGRectMake(20, 0, contentView.width-40, contentView.height);
    [contentView addSubview:label];
    return header_view;
}
- (void)layoutTableView {
    [super layoutTableView];
    CGFloat height =  SCREEN_HEIGHT-BottomSafeHeight-44-30;
    self.tableView.frame=CGRectMake(0, 0,SCREEN_WIDTH,height);
}

#pragma mark - <QMUITableViewDataSource, QMUITableViewDelegate>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    VideoModel * model = self.dataArray[indexPath.row];
    return model.cellHeight;
}
#pragma mark UITableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"UploadVideoCell";
    UploadVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UploadVideoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

- (void)add_bottom_view {
     CGFloat top =  SCREEN_HEIGHT-BottomSafeHeight-44-30;
    UIView * bottom_view = [[UIView alloc] initWithFrame:CGRectMake(0, top, SCREEN_WIDTH, BottomSafeHeight+44+30)];
    bottom_view.backgroundColor = self.tableView.backgroundColor ;
    [self.view addSubview:bottom_view];
    SubmitBtnViewShowType showType = Show_Uploading_type; //上传中状态
   
    self.bottom_btn = [[SubmitBtnView alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH-40, 44)];
    self.bottom_btn.showType = showType;
    @weakify(self);
    [self.bottom_btn setBtnClick_block:^{
        @strongify(self);
        [self bottomBtnClicked];
    }];
    [bottom_view addSubview:self.bottom_btn];
    
}

- (void)bottomBtnClicked {
    if (self.bottom_btn.showType == Show_retry_submit_type) {//重新提交
         [self start_upload];//开始上传
    }
}



#pragma mark 开始上传
- (void)start_upload {
    self.bottom_btn.showType == Show_Uploading_type;
    for (VideoModel *model in self.dataArray) {//全部设置为上传中状态
         if (model.showType == Cell_show_Upload_complete_type) {
             continue;
         }
          model.Upload=YES;
          model.showType=Cell_show_Uploading_type;
      }
    [self.tableView reloadData];
//    [QMUITips showLoading:@"视频处理中请稍后..." inView:self.view];
    
    dispatch_group_t group_t = dispatch_group_create();//创建线程组
    dispatch_queue_t queue = dispatch_queue_create("my_image_queue", DISPATCH_QUEUE_SERIAL);//创建串行队列
    dispatch_group_async(group_t, queue, ^{
        dispatch_group_enter(group_t);//进入总任务
        [VideoModel get_video_coverImages:self.dataArray];//获取封面 image
        dispatch_group_leave(group_t);
        GDLog(@"获取视频封面完成");
    });
    
     dispatch_group_async(group_t, queue, ^{
         [self get_video_image_url_dispatch_group:group_t];//上传图片
          GDLog(@"上传视频封面完成");
     });
    
    dispatch_group_async(group_t, queue, ^{
        [self video_compression_dispatch_group:group_t];//压缩视频
          GDLog(@"视频压缩完成");
//        dispatch_async(dispatch_get_main_queue(), ^{//回到主线程
//            [QMUITips hideAllTipsInView:self.view];
//        });
    });

    dispatch_group_async(group_t, queue, ^{
        [self upload_video_dispatch_group:group_t];//长传视频
        GDLog(@"上传视频完成");
    });
    
    dispatch_group_notify(group_t, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{//回到主线程
            GDLog(@"完成所有任务 %@",self.dataArray);
           if ([VideoModel is_all_uplod_successful_array:self.dataArray]) {//视频全部上传成功后
                  [self performSelector:@selector(complete_test)];//完成考试
              } else {
                  [self performSelector:@selector(error_set)];//错误处理
              }
        });
    });
}


#pragma mark  上传视频封面
/// 上传视频封面
/// @param total_group  总任务线程组
- (void)get_video_image_url_dispatch_group:(dispatch_group_t)total_group {
    NSMutableArray * dataArray = [self valueForKey:@"dataArray"];

    dispatch_group_enter(total_group);//进入总任务
    dispatch_group_t group_t = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("my_image_queue", DISPATCH_QUEUE_CONCURRENT);
    for (VideoModel *model in dataArray) {//全部设置为上传中状态
        if ([model.coverImageUrl isHelpful]) {//判断视频封面url存在直接跳过，用于长传失败时的处理
            continue;
        }
        if (self.cancel_upload) {//取消上传
             dispatch_group_leave(total_group);//离开本次任务
            break;
        }
        if (model.coverImage == nil) {
            dispatch_group_leave(total_group);//离开本次任务
            return;
        }
        dispatch_group_async(group_t, queue, ^{
            dispatch_group_enter(group_t);
            
            [model upload_video_coverImageSuccess:^(id obj) {
                dispatch_group_leave(group_t);
                GDLog(@"上传封面+++===");
            } error:^{
                dispatch_group_leave(group_t);
            }];
        });
    }
    dispatch_group_notify(group_t, queue, ^{
        dispatch_group_leave(total_group);
    });
}

#pragma mark  视频压缩
//视频压缩
///@param total_group   总任务线程组
- (void)video_compression_dispatch_group:(dispatch_group_t)total_group {
    NSMutableArray * dataArray = [self valueForKey:@"dataArray"];

    dispatch_group_enter(total_group);//进入视频压缩 总任务
    dispatch_queue_t queue = dispatch_queue_create("video_compression_queue", DISPATCH_QUEUE_SERIAL);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);//创建信号量
    for (VideoModel *model in dataArray) {//全部设置为上传中状态
        if ([model.compression_video_name isHelpful]) {//判断视频压缩后的名字是否存在 存在就是压缩过直接跳过
           dispatch_semaphore_signal(semaphore);//释放信号
           continue;
        }
        if (self.cancel_upload) {//取消上传
            dispatch_semaphore_signal(semaphore);//释放信号
            break;
        }
       dispatch_async(queue, ^{
            NSString * document_path = [model get_document_path];
            NSString * date_name = [model get_date_name];
            NSString *new_path = [NSString stringWithFormat:@"%@%@",document_path,date_name];//压缩视频路径
            [AppTools updata_video_path:[model get_original_path] new_path:new_path Success:^(NSString * _Nonnull path) {
                model.compression_video_name=date_name;//压缩的名也会存在沙盒里一份，上传成功时s再删除
                GDLog(@"压缩视频 %@ %@",[NSThread currentThread],model.name);
                 dispatch_semaphore_signal(semaphore);//释放信号
           } error:^{
               dispatch_semaphore_signal(semaphore);//释放信号
           }];
       });
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);//等待上个任务完成
    }
    //线程组 相关
     dispatch_group_leave(total_group); //离开结束任务
}
#pragma mark 视频上传
/// 视频上传
/// @param total_group   总任务线程组
- (void)upload_video_dispatch_group:(dispatch_group_t)total_group {

    dispatch_group_enter(total_group);//进入总任务
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    int i =0;
     @weakify(self);
    for (VideoModel *model in self.dataArray) {//全部设置为上传中状态
         if ([model.videoUrl isHelpful]) {//判断视频url存在直接跳过，用于长传失败时的处理
              dispatch_semaphore_signal(semaphore);
             continue;
         }
         if (self.cancel_upload) {//取消上传
            dispatch_semaphore_signal(semaphore);//释放信号
            break;
        }
           [[AliOSSObjctManage sharedInstance] uploadVideoWithVideoPath:[model get_compression_path] urlName:[model set_oss_url_pathName] progressBlock:^(CGFloat progress) {
               model.progress=progress;
               model.showType=Cell_show_Uploading_type;//上传中
               @strongify(self);
               [self refresh_uplod_progress_model:model];
           } Success:^(NSString * _Nonnull videoUrlStr) {
                  GDLog(@"上传成url %@",videoUrlStr);
                model.videoUrl=videoUrlStr;
                model.showType=Cell_show_Upload_complete_type;//上传完成
               model.videoUrl=videoUrlStr;
               @strongify(self);
               [self refresh_uplod_progress_model:model];
               dispatch_semaphore_signal(semaphore);
           } error:^{
               model.showType=Cell_show_Upload_error_type;//上传错误
               @strongify(self);
               [self refresh_uplod_progress_model:model];
                dispatch_semaphore_signal(semaphore);
           }];
         
         dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
     }
    dispatch_group_leave(total_group);//结束任务
}
#pragma mark 刷新行 上传进度
- (void)refresh_uplod_progress_model:(VideoModel *)model {
    UploadVideoCell *cell = (UploadVideoCell *)[self.tableView cellForRowAtIndexPath:model.indexPath];
    cell.model=model;
}

#pragma mark 错误处理
- (void)error_set {
    self.bottom_btn.showType = Show_retry_submit_type;
}
#pragma mark 完成考试
- (void)complete_test {
    if (self.cancel_upload) {//取消上传
        GDLog(@"取消上传了 ====");
        return;
    }
    [TestManageTool finish_test_orderId:self.orderId dataArray:self.dataArray success:^(id obj) {//完成考试
        [VideoModel remove_local_ModelArray_OrderId:self.orderId dataArray:self.dataArray];//上传成功后删除本地 原视频 和 压缩后的视频 都删除
        UploadSuccessController * vc = [[UploadSuccessController alloc] init];//跳转上传成功
        [self.navigationController pushViewController:vc animated:YES];
        
    } error:^{
      
    }];
}

#pragma mark 返回
- (void)leftNavItemClicked {
    [PopupWindow showType:Show_interrupt_test_type ClickBolck:^(NSInteger type) {
        if (type == 1) {
            self.cancel_upload = YES;
            self.navigationController.interactivePopGestureRecognizer.enabled=YES;//开启右滑返回
            for (UIViewController * vc in self.navigationController.viewControllers) {
                NSString * vcName = NSStringFromClass([vc class]);
                if ([vcName isEqualToString:@"OrderDetailsController"]) {
                    [self.navigationController popToViewController:vc animated:YES];
                    return;
                }
            }
            [self back_home_vc];
        }
    }];
}

#pragma mark 返回首页
- (void)back_home_vc {
    self.tabBarController.selectedIndex = 1;
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self performSelector:@selector(delay_load) withObject:nil afterDelay:0.7];
}
//延迟返回
- (void)delay_load {
    post_notification(to_order_details_vc_notice);//跳转订单详情界面通知
}

@end
